import { notFound } from 'next/navigation';
import { MDXRemote } from 'next-mdx-remote/rsc';
import { getDocBySlug, getDocsByCategory, getRelatedDocs } from '@/lib/docs';
import { DocsLayout } from '@/components/docs/docs-layout';
import { mdxComponents } from '@/components/mdx-components';
import rehypeSlug from 'rehype-slug';
import rehypeAutolinkHeadings from 'rehype-autolink-headings';
import remarkGfm from 'remark-gfm';

// 导入代码高亮样式
import 'highlight.js/styles/github-dark.css';

interface DocPageProps {
  params: {
    slug: string[];
  };
}

/**
 * 动态文档页面
 * 根据URL路径展示对应的MDX文档内容
 */
export default async function DocPage({ params }: DocPageProps) {
  // 构建文档slug
  const slug = params.slug.join('/');

  // 获取文档数据
  const doc = getDocBySlug(slug);

  if (!doc) {
    notFound();
  }

  // 获取文档分类和相关文档
  const categories = getDocsByCategory();
  const relatedDocs = getRelatedDocs(doc, 4);

  return (
    <DocsLayout doc={doc} categories={categories} relatedDocs={relatedDocs}>
      <MDXRemote
        source={doc.content}
        components={mdxComponents}
        options={{
          mdxOptions: {
            remarkPlugins: [remarkGfm],
            rehypePlugins: [
              rehypeSlug,
              [
                rehypeAutolinkHeadings,
                {
                  behavior: 'wrap',
                  properties: {
                    className: ['anchor'],
                  },
                },
              ],
            ],
          },
        }}
      />
    </DocsLayout>
  );
}

/**
 * 生成静态路径
 * 为所有文档生成静态页面
 */
export async function generateStaticParams() {
  try {
    const { getAllDocs } = await import('@/lib/docs');
    const docs = getAllDocs();

    return docs.map(doc => ({
      slug: doc.slug.split('/'),
    }));
  } catch (error) {
    console.warn('Failed to generate static params for docs:', error);
    return [];
  }
}

/**
 * 生成页面元数据
 * 为SEO优化提供动态元数据
 */
export async function generateMetadata({ params }: DocPageProps) {
  const slug = params.slug.join('/');
  const doc = getDocBySlug(slug);

  if (!doc) {
    return {
      title: '文档未找到 - CActor',
      description: '请求的文档页面不存在',
    };
  }

  return {
    title: `${doc.meta.title} - CActor 文档`,
    description: doc.meta.description,
    keywords: doc.meta.tags?.join(', '),
    authors: doc.meta.author ? [{ name: doc.meta.author }] : undefined,
    openGraph: {
      title: doc.meta.title,
      description: doc.meta.description,
      type: 'article',
      publishedTime: doc.meta.publishedAt,
      modifiedTime: doc.meta.updatedAt,
      authors: doc.meta.author ? [doc.meta.author] : undefined,
      tags: doc.meta.tags,
    },
    twitter: {
      card: 'summary_large_image',
      title: doc.meta.title,
      description: doc.meta.description,
    },
    alternates: {
      canonical: `/docs/${slug}`,
    },
  };
}
